package com.example.demo.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.example.demo.data.WeiboUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xcx
 * @date 2023/2/18 20:17
 */
@Controller
@Slf4j
public class GiteeController {

    @RequestMapping("/login/success")
    public String authorize(String code, HttpSession session) throws Exception {
//        683d283867bbc7435fd84d9fbd2eac7d168e5ee2894dc4d7b4ea8bce5e890868
//        c995d4c4a50d3e49ac25d8f5c3440c5bd1ffc9555471f5b4a53bc3f624c61921
        // 使用code换取token，换取成功则继续，否则重定向登录页
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("client_id", "683d283867bbc7435fd84d9fbd2eac7d168e5ee2894dc4d7b4ea8bce5e890868");
        paramMap.put("client_secret", "c995d4c4a50d3e49ac25d8f5c3440c5bd1ffc9555471f5b4a53bc3f624c61921");
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("redirect_uri", "https://www.xingchenxu.top/auth/login/success");
        paramMap.put("code", code);
        String url = this.buildUrl("https://gitee.com", "/oauth/token", paramMap);
        //发送post请求换取token
        HttpResponse httpResponse = HttpRequest.post(url)
                .timeout(20000)//超时，毫秒
                .execute();

        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            log.info("body: {}", body);
            WeiboUser weiboUser = JSONUtil.toBean(body, WeiboUser.class);
            // 将用户信息返回
            session.setAttribute("userInfo", weiboUser.toString());
            String access_token = weiboUser.getAccess_token();
            HttpRequest httpRequest = HttpRequest.get("https://gitee.com/api/v5/user?access_token=" + access_token);
            log.info(httpRequest.execute().body());
            session.setAttribute("userInfo", httpRequest.execute().body());
        }
        return "home";
    }

    @GetMapping("refresh/{refresh_token}")
    public String refresh(@PathVariable String refresh_token){
        HttpRequest httpRequest = HttpRequest.get("https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token=" + refresh_token);
        log.info(httpRequest.execute().body());
        return "home";
    }

    private static String buildUrl(String host, String path, Map<String, Object> querys) throws
            UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host).append(path);

        StringBuilder sbQuery = new StringBuilder();

        for (Map.Entry<String, Object> query : querys.entrySet()) {
            if (sbQuery.length() > 0) {
                sbQuery.append("&");
            }
            sbQuery.append(query.getKey());
            sbQuery.append("=");
            sbQuery.append(URLEncoder.encode(query.getValue().toString(), "utf-8"));
        }

        if (sbQuery.length() > 0) {
            sbUrl.append("?").append(sbQuery);
        }

        return sbUrl.toString();
    }
}
